#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import string
import shutil
import global_var
import MySQLdb
from mod_python import util,Session,Cookie

import time
import sys
reload(sys)
sys.setdefaultencoding('utf8')

__dir__         = os.path.dirname(__file__)

def display(req, user_name):
	req.content_type = 'image/jpg'
	conn = MySQLdb.connect(user=global_var.mysql_user, passwd=global_var.mysql_password, host=global_var.mysql_host, port=global_var.mysql_port)
	cursor = conn.cursor()
	conn.select_db(global_var.mysql_database)
	cursor.execute("""select user_id from user where user_name=%s""", user_name)
	row = cursor.fetchone()
	user_id = -1
	if row == None:
		body = ''
		return body
	else:
		user_id = row[0]
	file_path = os.path.join(__dir__, 'tmp/' + str(user_id) + '/') 
	for file in os.listdir(os.path.join(__dir__, file_path)):
		if not os.path.isdir(file):
			try:
				num = string.atoi(os.path.basename(file))
				if num < min_num:
					min_num = num

			except:
				continue
	main_pic = ''	
	min_num = 0
	if min_num != 0 and not os.path.exists(os.path.join(__dir__, 'tmp/' + str(user_id) + '/0')):
		main_pic = 'tmp/' + str(min_num)
	elif os.path.exists(os.path.join(__dir__, 'tmp/' + str(user_id) + '/0')):
		main_pic = 'tmp/' + str(user_id) + '/0'
	
	if main_pic != '':	
		f = open(os.path.join(__dir__, main_pic), 'r')
		body = f.read()
		f.close()
		req.content_type = str('image/jpg')
	else:
		body = ''

	return body

def userurl_display(req):
	req.content_type = 'text/html'
	body = ''
	if isinstance( req.form['user_url'], basestring ) and req.form['user_url'] != '':
		user_url= req.form['user_url']
		f = open( os.path.join(__dir__, 'template/api_example.html'), 'r' )
		api_example = f.read()
		f.close()
		body = api_example % {'url':user_url}
	else:
		body = u'url type is invalid'

	return body
